<template>
  <div class="family-messages">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>消息中心</span>
          <el-button type="primary" @click="showSendDialog = true">
            <el-icon><Message /></el-icon>
            发送消息
          </el-button>
        </div>
      </template>

      <!-- 消息列表 -->
      <div class="message-list">
        <div v-for="message in messages" :key="message.messageId" class="message-item" 
             :class="{ 'unread': !message.isRead }">
          <div class="message-header">
            <div class="sender-info">
              <el-avatar :size="40" :src="message.senderAvatar || '/avatars/default-avatar.png'">
                {{ message.senderName?.charAt(0) }}
              </el-avatar>
              <div class="sender-details">
                <div class="sender-name">{{ message.senderName }}</div>
                <div class="message-time">{{ formatTime(message.createTime) }}</div>
              </div>
            </div>
            <el-tag :type="getMessageTypeTag(message.messageType)" size="small">
              {{ getMessageTypeText(message.messageType) }}
            </el-tag>
          </div>
          <div class="message-content">
            {{ message.content }}
          </div>
          <div class="message-actions" v-if="message.senderRole !== 'family'">
            <el-button size="small" @click="replyMessage(message)">回复</el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发送消息对话框 -->
    <el-dialog v-model="showSendDialog" title="发送消息" width="500px">
      <el-form :model="sendForm" label-width="80px">
        <el-form-item label="接收人">
          <el-select v-model="sendForm.receiverId" placeholder="请选择接收人" style="width: 100%">
            <el-option
              v-for="caregiver in caregivers"
              :key="caregiver.caregiverId"
              :label="`${caregiver.name} (护工)`"
              :value="caregiver.caregiverId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input
            v-model="sendForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSendDialog = false">取消</el-button>
        <el-button type="primary" @click="sendMessage" :loading="sending">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getFamilyMessages, sendMessageToCaregiver, getCaregiversByElder } from '@/api/message'

const messages = ref([])
const caregivers = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showSendDialog = ref(false)
const sending = ref(false)
const loading = ref(false)

const sendForm = reactive({
  receiverId: '',
  content: ''
})

// 加载消息列表
const loadMessages = async () => {
  loading.value = true
  try {
    const response = await getFamilyMessages({
      page: currentPage.value,
      size: pageSize.value
    })
    messages.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  } finally {
    loading.value = false
  }
}

// 加载护工列表
const loadCaregivers = async () => {
  try {
    const response = await getCaregiversByElder()
    caregivers.value = response.data || []
  } catch (error) {
    console.error('加载护工列表失败:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  if (!sendForm.receiverId) {
    ElMessage.warning('请选择接收人')
    return
  }
  if (!sendForm.content.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }

  sending.value = true
  try {
    await sendMessageToCaregiver(sendForm)
    ElMessage.success('消息发送成功')
    showSendDialog.value = false
    sendForm.receiverId = ''
    sendForm.content = ''
    loadMessages()
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 回复消息
const replyMessage = (message) => {
  sendForm.receiverId = message.senderId
  sendForm.content = `回复 ${message.senderName}：`
  showSendDialog.value = true
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 获取消息类型标签
const getMessageTypeTag = (type) => {
  const typeMap = {
    'NOTICE': 'info',
    'REMINDER': 'warning',
    'URGENT': 'danger',
    'NORMAL': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取消息类型文本
const getMessageTypeText = (type) => {
  const typeMap = {
    'NOTICE': '通知',
    'REMINDER': '提醒',
    'URGENT': '紧急',
    'NORMAL': '普通'
  }
  return typeMap[type] || '普通'
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadMessages()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMessages()
}

onMounted(() => {
  loadMessages()
  loadCaregivers()
})
</script>

<style scoped>
.family-messages {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-list {
  max-height: 600px;
  overflow-y: auto;
}

.message-item {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-item.unread {
  background-color: #f0f9ff;
  border-left: 3px solid #409eff;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sender-details {
  display: flex;
  flex-direction: column;
}

.sender-name {
  font-weight: 600;
  color: #303133;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.message-actions {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
